package com.flex.showdoc4j.executor;


import com.flex.showdoc4j.executor.interfaces.ClientExecutor;
import com.flex.showdoc4j.executor.interfaces.ParameterResolver;
import com.flex.showdoc4j.http.HttpClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.HttpClientErrorException;

import java.util.List;

/**
 * http执行方法
 *
 * @author ganlt<br>
 * @since 2019/06/26 16:20 <br>
 */
@Slf4j
public class HttpClientExecutor implements ClientExecutor {
    /**
     * 失败重试次数
     */
    private int retryCount = 1;

    @Override
    public String executor(Wrapper wrapper) throws HttpClientErrorException {
        int retry = wrapper.getConfiguration().getConfigModel().getRetryCount();
        if (retry > 0) {
            retryCount = retry;
        } else {
            retryCount = 1;
        }

        String url = wrapper.getUrl();
        return doExecutor(url, wrapper);
    }

    public String doExecutor(String url, Wrapper wrapper) throws HttpClientErrorException {
        //解析出参数
        ParameterResolver parameterResolver = wrapper.getConfiguration().getParameterResolver();
        List<?> resolvers = parameterResolver.resolver(wrapper);
        String body = "";
        if (resolvers.size() > 1) {
            body = JSON.toJSONString(resolvers);
        } else if (resolvers.size() == 1) {
            body = JSON.toJSONString(resolvers.get(0));
        }
        JSONObject parseObject = JSON.parseObject(body);
        for (int i = 0; i <= retryCount; i++) {
            try {
                String resultBody = HttpClient.doPost(url, parseObject);
                log.info(resultBody);
            } catch (Exception e) {
                log.error("调用失败,尝试第{}次调用", i);
                try {
                    Thread.sleep(500);
                    doExecutor(url, wrapper);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return "";
    }
}
